﻿using System;
using UnityEngine;
using System.Collections.Generic;
using System.Threading;

public class NetProc : MonoBehaviour
{
    static NetProc _ins;
    public static NetProc Ins
    {
        get
        {
            return _ins;
        }
    }
    //---------------------------------------------------------
    // 服务器 IP
    const string serverIp = "127.0.0.1";
    // 端口号
    const int port = 26720;
    //---------------------------------------------------------
    // tcp网络
    TcpClientEx client;
    //---------------------------------------------------------
    /// <summary>
    /// 网络断开 回调事件
    /// </summary>
    public System.Action OnDisconnect;

    // 消息队列
    List<byte[]> msgQueue = new List<byte[]>();
    object msgloker = new object();

    /// <summary>
    /// 是否已经连接
    /// </summary>
    public bool Connected
    {
        get
        {
            return client.Connected;
        }
    }


    void Awake()
    {
        // 注册实例
        _ins = this;

        // 设置不销毁
        DontDestroyOnLoad(gameObject);


        // 连接断开后提示
        OnDisconnect += () =>
        {
            Debug.LogWarning("与主服务器断开连接");
        };


        // Tcp 客户端
        client = new TcpClientEx();
        client.OnDisconnect += () =>
        {
            lock (msgloker)
            {
                msgQueue.Insert(0, null);
            }
        };

        client.OnMsgReceived += (byte[] byteMsg) =>
        {
            lock (msgloker)
            {
                msgQueue.Add(byteMsg);
            }
        };
        //// 开始连接服务器
        //Thread td = new Thread(connectServer);
        //td.IsBackground = true;
        //td.Start();

    }

    void Update()
    {
        //----------------------------------
        // 消息
        lock (msgloker)
        {
            foreach (var msg in msgQueue)
            {
                if (msg == null)
                {
                    if (OnDisconnect != null) OnDisconnect.Invoke();
                    msgQueue.Clear();
                    break;
                }
                else
                {
                }
            }
            if (msgQueue.Count > 0)
                msgQueue.Clear();
        }
    }

    // 连接服务器
    void connectServer()
    {
        if (client.Connect(serverIp, port))
        {
            Debug.Log("连接Lobby成功！");
        }
        else lock (msgloker)
            {
                msgQueue.Insert(0, null);
            }
    }

    void OnDestroy()
    {
        client.Disconnect();
    }


    // 重新连接
    public void StartConnect()
    {
        // 开始连接服务器
        Thread td = new Thread(connectServer);
        td.IsBackground = true;
        td.Start();
    }

    public void SendFps(ushort fps)
    {
        if (!client.Connected)
        {
            connectServer();
            return;
        }
        byte[] bfps = BitConverter.GetBytes(fps);
        client.Send(bfps);
    }
}
